import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_image_compress/flutter_image_compress.dart';
import 'package:jetour_line/utils/aha_utils.dart';
import 'package:jetour_line/utils/video_utils.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';
import '../aha_manger.dart';
import '../models/jetour_line_detail.dart';
import '../models/public_msg_manger.dart';
import '../utils/crypto_util.dart';
import '../utils/login_utils.dart';

class _HttpConfig {
  static const int timeout = 20000;
  static const String appId = "1669687766";
  static const String appSecret = "42967910268c1e3609c6eb4b4d67bd66";
  static const String publicKey =
      "-----BEGIN PUBLIC KEY-----\nMFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAK//smpd9HTfqV95z5tJBE5L60PDt9Ou\n8CvFovKZ96sBNVfNxm2+22Ew79+bv0Cw7qEmqUGH9oDKHSc8CTc0bL8CAwEAAQ==\n-----END PUBLIC KEY-----";
}

class JetourRouter {
  //首页
  static const String IndexSwiperList = "/ahatrip/guide/index-swiper";
  //共创路书列表
  static const String UserGuideList = "/ahatrip/guide/list";
  static const String CommonDetail = "/ahatrip/guide/detail";//共创路书详情 - 捷途
  static const String CommonCollect = "/ahatrip/guide/collect";//收藏共创路书 - 捷途
  static const String GuideToolAddNode = "/ahatrip/guide-tool/add-node";//将阿哈POI添加到行程点 - 捷途
  static const String GuideToolAddNodeByContent = "/ahatrip/guide-tool/add-node-by-content";//将高德POI添加至行程点
  static const String GuideToolInit = "/ahatrip/guide-tool/init";//路书初始化 - 捷途
  static const String GuideToolNodeDetail = "/ahatrip/guide-tool/node-detail";//  获取行程点详情
  static const String GuideToolSaveNodeDetail = "/ahatrip/guide-tool/save-node-detail";//修改行程点信息
  static const String GuideToolDetail = "/ahatrip/guide-tool/detail";//获取路书详情 - 捷途
  static const String GuideToolDeleteDay = "/ahatrip/guide-tool/delete-day";//删除X天 - 捷途
  static const String GuideToolDeletNode = "/ahatrip/guide-tool/delete-node";//删除第x点 - 捷途
  static const String GuideMyGuide = "/ahatrip/guide/my-guide";//我的共创列表 - 捷途
  static const String GuideDelete = "/ahatrip/guide/delete";//删除我的共创 - 捷途
  static const String GuideMyCollect = "/ahatrip/guide/my-collect";//收藏列表 - 共创
  static const String GuideFinishLine = "/ahatrip/guide-tool/finish-line";//结束编辑路书 - 捷途
  static const String GuideUploadVideo = "/ahatrip/guide-tool/upload-video";//上传视频 - 捷途
  static const String GuideCateList = "/ahatrip/guide/cate-list";//共创路书分类列表 - 捷途

}

class JetourHttp {
  late final Dio dio;
  JetourHttp._internal() {
    String baseUrl =  "https://roadbook.jetour.com.cn" ;
    if(kReleaseMode){
      if(AhaManger().isUat){
        baseUrl =  'http://jetour.ahatrip.net';
      }else{
        baseUrl =  "https://roadbook.jetour.com.cn" ;
      }
      // baseUrl =  "https://roadbook.jetour.com.cn" ;
    } else{
      if(AhaManger().isUat){
        baseUrl =  'http://jetour.ahatrip.net';
      }else{
        baseUrl =  "https://roadbook.jetour.com.cn" ;
      }
    }

    final config = BaseOptions(baseUrl: baseUrl, connectTimeout: _HttpConfig.timeout);
    dio = Dio(config);
    Interceptor commonInterceptor =
    InterceptorsWrapper(onRequest: (RequestOptions options, RequestInterceptorHandler handler) {
      String date = DateTime.now().millisecondsSinceEpoch.toString();
      date = date.substring(0, date.length - 3);
      String crypto = _HttpConfig.appId + _HttpConfig.appSecret + date;
      // todo token
      options.headers.addAll({"t": date, "sign": CryptoUtil.string2Md5(crypto), 'appId': _HttpConfig.appId});
      if(PublicMsgManger().userInfoModel != null){
        options.headers.addAll({
          "token": PublicMsgManger().userInfoModel!.token,
        });
      }
      handler.next(options);
    }, onResponse: (Response response, ResponseInterceptorHandler handler) async {
      Map<dynamic, dynamic> dataMap = response.data;
      if (dataMap['code'] == 0) {
        return handler.next(response);
      } else if (dataMap["code"] == 9999) {
        // Utils.showToast('您的账户已在其它设备登录，请重新登录');
        LoginUtils.logOut();
        // eventBus.fire(ChangeUserInfo());
        //

        //阿哈从新登陆，获取jetourtoken，获取阿哈token

        //重新请求
        // Response<dynamic> newResponse = await get(response.requestOptions.path,
        //     params: response.requestOptions.queryParameters,
        //     context: response.requestOptions.extra['context'],
        //     headers: response.requestOptions.headers);

        // return handler.next(newResponse);
        return handler.next(response);
      } else {
        String msg = dataMap['msg'];
        if(!msg.contains('http')&& !msg.contains('error')){
          AhaUtils.showTxt(msg);
        }
        return handler.next(response);
      }
    });
    dio.interceptors.add(commonInterceptor);
  }
  static final _instance = JetourHttp._internal();

  factory JetourHttp() => _instance;

  Future get(url, {Map<String, dynamic>? params, BuildContext? context, Map<String, dynamic>? headers}) async {
    final options = Options(headers: headers, extra: {'context': context});
    try {
      Response<dynamic> response = await dio.get(url, queryParameters: params, options: options);
      Map<dynamic, dynamic> dataMap = response.data;
      // print('getgetgetgetget====',)
      if (dataMap['code'] == 0){
        return dataMap["data"];
      }else{
        return null;
      }
    } on DioError catch (e) {
      return Future.error(e.message);
    }
  }

  Future post(url,
      {Map<String, dynamic>? params,
        Map<String, dynamic>? data,
        BuildContext? context,
        Map<String, dynamic>? headers}) async {
    final options = Options(headers: headers, extra: {'context': context});
    try {
      Response<dynamic> response = await dio.post(url, queryParameters: params, data: data, options: options);
      Map<dynamic, dynamic> dataMap = response.data;
      if (dataMap['code'] == 0){
        return dataMap["data"];
      }else{
        return null;
      }
    } on DioError catch (e) {
      return Future.error(e.message);
    }
  }
  // 压缩图片
  static Future<File?> compressImage(File file, {int quality = 60}) async {
    String path = file.path;
    path = path.replaceAll('.jpg','compress.jpg');
    path = path.replaceAll('.JPG','compress.JPG');
    path = path.replaceAll('.png','compress.png');
    path = path.replaceAll('.gif','compress.gif');
    path = path.replaceAll('.GIF','compress.Gif');
    path = path.replaceAll('.bmp','compress.bmp');
    path = path.replaceAll('.BMP','compress.BMP');
    final result = await FlutterImageCompress.compressAndGetFile(file.path, path,quality: quality);
    return result;
  }

  // void main() {
  //   String originalString = 'Hello, world!';
  //   String stringToReplace = 'world';
  //   String replacementString = 'Flutter';
  //
  //   String replacedString = originalString.replaceAll(stringToReplace, replacementString);
  //
  //   print(replacedString); // 输出: Hello, Flutter!
  // }

  Future upImages(List images) async {
    if(images.isEmpty ){
      return null;
    }
    String url = '/ahatrip/guide-tool/upload-images';
    List<String> imgUrl = [];
    try {
      Map<String, dynamic> imgMaps =  Map();

      for(int i = 0;i<images.length;i++)
      {
        if(images[i].runtimeType != String){
          File file = await compressImage(images[i]) as File ;
          var name = file.path.substring(file.path.lastIndexOf("/") + 1, file.path.length);
          imgMaps["photo$i"] = await MultipartFile.fromFile(file.path, filename: name);
        }else{
          imgUrl.add(images[i]);
        }
      }
      if(imgMaps.isEmpty){
        return imgUrl;
      }
      FormData formdata = FormData.fromMap(imgMaps);

      Response<dynamic> response = await dio.post(url,data: formdata);

      Map<dynamic, dynamic> dataMap = response.data;

      List data = dataMap["data"] ;
      for(int i = 0;i<data.length;i++){
        imgUrl.add(data[i]);
      }

      return imgUrl;
    } on DioError catch (e) {
      return Future.error(e.message);
    }
  }

  Future upVideo(var video) async {
    File? file ;
    if(video.runtimeType == AssetEntity){
      AssetEntity assetEntity = video;
      file = await assetEntity.file;
    }else if(video.runtimeType == Videos){
      Videos videos = video;
      Map<dynamic, dynamic> videoMap = {};
      videoMap['url'] = videos.url;
      videoMap['frame'] = videos.frame;
      return videoMap;
    }

    if (file!.lengthSync() > 104857600*2) {
      AhaUtils.showTxt('当前视频文件过大，请编辑视频后再次上传');
      return;
    }
    await VideoUtils.compressVideo(file.path, file.path);
    try {
      String path = file.path;
      var fileName = path.substring(path.lastIndexOf("/") + 1, path.length);
      MultipartFile multipartFile =
      MultipartFile.fromFileSync(path, filename: fileName);
      FormData formData =  FormData.fromMap({
        "video": multipartFile,
      });
      Response<dynamic> response = await dio.post(JetourRouter.GuideUploadVideo,data: formData);
      Map<dynamic, dynamic> dataMap = response.data;
      Map<dynamic, dynamic> data = dataMap["data"];
      print("data = === $data");
      return data;
    } on DioError catch (e) {
      return Future.error(e.message);
    }
  }

}
